package com.byt;

import cn.hutool.core.util.RuntimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Cpu部分代码参考 https://blog.csdn.net/java2000_net/article/details/3136124
 *
 * @author jxlhl
 */
public class CpuServer {
    private static Logger logger = LoggerFactory.getLogger(CpuServer.class);

    //cpu消耗方法
    public static void cpuConsume() {
        // 角度的分割
        final double SPLIT = 0.01;
        //
        // 2PI分割的次数，也就是2/0.01个，正好是一周
        final int COUNT = (int) (2 / SPLIT);
        final double PI = Math.PI;
        // 时间间隔
        final int INTERVAL = 200;
        long[] busySpan = new long[COUNT];
        long[] idleSpan = new long[COUNT];
        int half = INTERVAL / 2;
        double radian = 0.0;
        for (int i = 0; i < COUNT; i++) {
            busySpan[i] = (long) (half + (Math.sin(PI * radian) * half));
            idleSpan[i] = INTERVAL - busySpan[i];
            radian += SPLIT;
        }
        long startTime = 0;
        int j = 0;
        while (true) {
            try {
                double cpu =cpuInfo();
                if (cpu > 60) {
                    logger.info("CPU使用率过高：" + cpu);
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            j = j % COUNT;
            startTime = System.currentTimeMillis();
            while (System.currentTimeMillis() - startTime < busySpan[j]);
            try {
                //这里的if控制可以注解掉，让Thread.sleep(idleSpan[j])一直执行。
                //我这里加了if控制是因为希望Cpu一直保存在70%以上工作的效果(小于70不sleep)，If注解掉将以正弦曲线的趋势使用Cpu
                if (idleSpan[j] < 70) {
                    Thread.sleep(idleSpan[j]);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            j++;
        }
    }

    /**
     * 验证cpu是否过大
     * @return
     */
    public static double cpuInfo(){
        String command1 = "top -b -n 1 | grep Cpu";
        //执行该命令 截取到Cpu信息这一行的数据
        String[] command = { "/bin/sh", "-c", command1 };
        //hutool工具对执行命令的封装
        String s = RuntimeUtil.execForStr(command);
        if(s!=null && !"".equals(s)){
            String num1 = s.substring(s.indexOf(":")+1,s.indexOf("us"));
            String num2 = s.substring(s.indexOf("us,")+3,s.indexOf("sy"));
            num1 = num1.replace(" ", "");
            num2 = num2.replace(" ", "");
            return Double.parseDouble(num1)+Double.parseDouble(num2);
        }
        return 0;
    }

}


